import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 创建axios
const service = axios.create({
  // api的baseUrl
  baseURL: process.env.VUE_APP_HHTP_IP,
  // 请求超时时间
  timeout: 50000
})
const isAgainLogin = { isAgain: false }
// error信息
const errorInfo = {
  '401': '认证失败，无法访问系统资源',
  '403': '当前操作没有权限',
  '404': '访问资源不存在',
  'default': '系统未知错误，请反馈给管理员'
}

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 设置每个请求携带token
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer-' + getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const code = response.data.code
    const success = response.data.success
    const data = response.data
    const errorMessage = errorInfo[code] || response.data.message
    if (code === 200 || success) {
      return data
    } else if (code === 401) {
      if (!isAgainLogin.isAgain) {
        MessageBox.confirm('登录已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
        ).then(() => {
          isAgainLogin.isAgain = false
          store.dispatch('resetToken').then(() => {
            location.reload()
          })
        }).catch(err => {
          isAgainLogin.isAgain = false
          Message({
            message: err || 'Error',
            type: 'error'
          })
        })
      }
      return Promise.reject('会话已过期，请重新登录。')
    } else if (code === 403) {
      Message({
        message: errorMessage || 'Error',
        type: 'error'
      })
      return Promise.reject('error')
    } else if (code === 500) {
      Message({
        message: errorMessage || 'Error',
        type: 'error'
      })
      return Promise.reject(new Error(errorMessage))
    } else {
      Message({
        message: errorMessage || 'Error',
        type: 'error'
      })
      return Promise.reject('error')
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
